package com.starryx.driverschool.controller;

import com.starryx.driverschool.po.User;
import com.starryx.driverschool.service.UserService;
import com.starryx.driverschool.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.SpringVersion;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @GetMapping("/login/post")
    public String toLogin(){
        return "redirect:/login";
    }

    @PostMapping("/login/post")
    public String loginPost(
            @RequestParam String username,
            @RequestParam String password,
            HttpSession session,
            RedirectAttributes attributes){
        User user = userService.checkUser(username, MD5Utils.code(password), true);
        if(user != null){
            user.setPassword(null);
            session.setAttribute("user", user);
            return "redirect:/index";
        }else{
            attributes.addFlashAttribute("message", "用户名和密码错误");
            return "redirect:/login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/login";
    }

}
